package com.sigmatrix.h5.web.controller.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sigmatrix.h5.redisson.DistributedLocker;
import com.sigmatrix.h5.redisson.DistributedObject;
import com.sigmatrix.h5.redisson.LockedWorker;
import com.sigmatrix.h5.web.BaseController;

/**
 * redisson相关。测试mybatic常用操作
 * 
 * @author wei.wang
 *
 */
@RestController
@RequestMapping("/util/test/redisson")
public class TestRedissonController extends BaseController {

	@Autowired
	private DistributedLocker distributedLocker;
	@Autowired
	private DistributedObject distributedObject;
	
	private final static String KEY = "key";
	private final static String QUEUE_NAME = "myqueue";

	//
	@GetMapping("/lock/1")
	public void testLocker1() {
		lockOneKey();
	}
	
	@GetMapping("/lock/2")
	public void testLocker2() {
		lockOneKey();
	}
	
	@GetMapping("/queue/offer")
	public void testQueueOff() {
		String xxx = "xxxxx"+Thread.currentThread();
		distributedObject.offer(QUEUE_NAME, xxx);
	}
	
	@GetMapping("/queue/peek")
	public Object testQueuePeek() {
		return distributedObject.peek(QUEUE_NAME);
	}
	
	@GetMapping("/queue/poll")
	public Object testQueuePoll() {
		return distributedObject.poll(QUEUE_NAME);
	}

	private void lockOneKey() {
		boolean available = distributedLocker.isAvailable(KEY);
		System.err.println(KEY+"是否可用： "+available);
		if(!available){
			return;
		}
		LockedWorker<Void> worker = new LockedWorker<Void>() {

			@Override
			public Void invokeAfterLocked() {
				System.err.println( Thread.currentThread().getName()+" 被锁住。当前时间"+System.currentTimeMillis());
				try {
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.err.println( Thread.currentThread().getName()+" 当前锁将被释放 当前时间"+System.currentTimeMillis());
				return null;
			}
		};
		
		distributedLocker.lockAndInvoke(KEY, worker, 50000);
	}
	
}
